<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-07-18 16:17:37
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\slide\slide.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="登记时间" prop="formDate">
            <el-date-picker
              v-model="queryParams.formDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              clearable
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="剂量元件码"
            prop="slidesNumber"
            label-width="120px"
          >
            <el-input
              v-model="queryParams.slidesNumber"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="operation">
      <el-button
        class="register"
        type="primary"
        size="mini"
        @click.native.prevent="openDialog()"
        >登记</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      :data="slidesList"
      :height="height - 400 + 'px'"
      @row-dblclick="(row) => openDialog(row, '3')"
    >
      <el-table-column label="剂量元件码" align="center" prop="slidesNumber" />
      <el-table-column
        label="对照样品"
        align="center"
        prop="registrationSlidesSampleName"
      />
      <el-table-column label="登记时间" align="center" prop="detectionTime" />
      <el-table-column label="读出值1" align="center" prop="holeOne" />
      <el-table-column label="系数1" align="center">
        <template slot-scope="{ row }">
          {{ (row.holeOneCoefficient * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="读出值2" align="center" prop="holeTwo" />
      <el-table-column label="系数2" align="center">
        <template slot-scope="{ row }">
          {{ (row.holeTwoCoefficient * 100).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button
            @click.native.prevent="handleDelete(row)"
            type="text"
            style="color: #f32d2d"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 登记弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="closeExam"
      width="70%"
      class="sampledialog"
      v-dialogDrag="true"
    >
      <div class="searchcontainer" :class="status == '3' && 'viewform'">
        <el-upload
          ref="upload"
          class="myupload"
          :action="upload.url"
          :headers="upload.headers"
          :data="upload.data"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleFileSuccessSecond"
          :auto-upload="true"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
          v-if="status != '3'"
        >
          <el-button
            class="uploadbutton"
            slot="trigger"
            icon="el-icon-folder"
            size="mini"
            type="primary"
            >导入</el-button
          >
        </el-upload>

        <el-form
          class="myform"
          :model="form"
          :disabled="status == '3'"
          ref="form"
          :rules="rules"
          size="small"
          label-width="100px"
        >
          <el-form-item label="对照样品" prop="registrationSlidesSampleId">
            <el-select
              v-model="form.registrationSlidesSampleId"
              placeholder="请选择"
              @change="handleChangeSample"
            >
              <el-option
                :label="item.name"
                :value="item.registrationSlidesSampleId"
                v-for="(item, index) in slidesSamplesSelect"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="loadingCalculate"
        :data="importDataList"
        height="550"
      >
        <el-table-column
          label="剂量元件码"
          align="center"
          prop="slidesNumber"
        />
        <el-table-column label="检测时间" align="center" prop="detectionTime" />
        <el-table-column label="读出值1" align="center" prop="holeOne" />
        <el-table-column label="系数1" align="center">
          <template slot-scope="{ row }">
            {{ (row.holeOneCoefficient * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="读出值2" align="center" prop="holeTwo" />
        <el-table-column label="系数2" align="center">
          <template slot-scope="{ row }">
            {{ (row.holeTwoCoefficient * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column v-if="status != '3'" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteData(scope.$index)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer">
        <el-button
          type="primary"
          :disabled="importDataList.length == 0"
          v-if="status != '3'"
          @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看弹框 -->
    <el-dialog
      title="查看剂量元件"
      :visible.sync="dialogVisibleView"
      :close-on-click-modal="false"
      class="viewbind"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        disabled
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="剂量元件码">
              <el-input v-model="form.slidesNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="对照样品">
              <el-input v-model="form.registrationSlidesSampleName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登记时间">
              <el-input v-model="form.detectionTime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="孔一值">
              <el-input v-model="form.holeOne" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孔一系数">
              <el-input v-model="form.holeOneCoefficient" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="孔二值">
              <el-input v-model="form.holeTwo" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孔二系数">
              <el-input v-model="form.holeTwoCoefficient" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button @click="dialogVisibleView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  slidesSampleList,
  slidesSampleExport,
  slidesSampleListing,
  slidesSampleImport,
  slidesSampleDetail,
  slidesSampleCompute,
  slidesSampleAdd,
  slidesSampleEdit,
  slidesSampleDelete,
  slidesSampleUpdateState,
} from "@/api/slides/slideSample";
import {
  slidesList,
  slidesExport,
  slidesListing,
  changeSample,
  slidesImport,
  slidesDetail,
  slidesAdd,
  slidesDelete,
} from "@/api/slides/slide";
import { getToken } from "@/utils/auth";

export default {
  name: "slide",
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 参数
        data: {
          registrationSlidesSampleId: null,
        },
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/basic/registration/slides/importData",
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 滑片列表
      slidesList: [],
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      // 导入后获取的数值列表
      importDataList: [],
      loadingResult: false,
      // 计算结果单条列表
      resultList: [],
      nameVisible: false,
      rules: {
        registrationSlidesSampleId: [
          { required: true, message: "对照样品不能为空", trigger: "change" },
        ],
      },
      // 滑片样品下拉框
      slidesSamplesSelect: [],
      dialogVisibleView: false,
      //
      defaultSamplesSelect: null,
      loadingCalculate: false,
    };
  },
  created() {
    this.getList();
    // 获取滑片样品下拉框
    this.getSlidesSampleSelect();
  },
  methods: {
    // 获取滑片列表
    getList() {
      this.queryParams.detectionTimeStart =
        this.queryParams.formDate && this.queryParams.formDate[0];
      this.queryParams.detectionTimeEnd =
        this.queryParams.formDate && this.queryParams.formDate[1];
      let queryParams = { ...this.queryParams };
      delete queryParams.formDate;
      this.loading = true;
      slidesList(queryParams)
        .then((response) => {
          this.slidesList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取滑片样品下拉框
    getSlidesSampleSelect() {
      slidesSampleListing().then((response) => {
        this.slidesSamplesSelect = response.data;
        if (response.data.length != 0) {
          this.defaultSamplesSelect =
            response.data[0].registrationSlidesSampleId;
        }
      });
    },
    // 更新状态
    updateState(row, state) {
      slidesSampleUpdateState({
        registrationSlidesSampleId: row.registrationSlidesSampleId,
        state: state,
      }).then((response) => {
        this.getList();
      });
    },
    // 打开对话框
    openDialog(row, status) {
      this.resetForm("form");
      this.form = {};
      this.upload.data = {
        registrationSlidesSampleId: null,
      };
      this.importDataList = [];
      this.resultList = [];
      if (row) {
        slidesDetail(row.registrationSlidesId).then((response) => {
          this.form = response.data;
          this.form.holeOneCoefficient =
            response.data.holeOneCoefficient &&
            (response.data.holeOneCoefficient * 100).toFixed(2) + "%";
          this.form.holeTwoCoefficient =
            response.data.holeTwoCoefficient &&
            (response.data.holeTwoCoefficient * 100).toFixed(2) + "%";
          this.dialogVisibleView = true;
        });
        if (status == "3") {
          this.status = "3";
          this.title = "查看剂量元件";
        } else {
        }
      } else {
        this.form = {
          registrationSlidesSampleId: this.defaultSamplesSelect,
        };
        this.upload.data.registrationSlidesSampleId = this.defaultSamplesSelect;
        this.status = "1";
        this.title = "添加剂量元件";
        this.dialogVisible = true;
      }
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        if (this.importDataList.length == 0) {
          this.$modal.msgWarning("请导入数据");
          return;
        }
        this.importDataList.forEach((item) => {
          delete item.registrationSlidesId;
          delete item.registrationSlidesSampleName;
        });
        let form = {
          registrationSlidesSampleId: this.form.registrationSlidesSampleId,
          registrationSlidesBos: this.importDataList,
        };
        slidesAdd(form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.getList();
        });
      });
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除剂量元件码 [${row.slidesNumber}] ？`)
        .then(() => {
          this.loading = true;
          return slidesDelete(row.registrationSlidesId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    deleteData(index) {
      this.$modal.confirm(`是否确认删除该数据？`).then(() => {
        this.importDataList.splice(index, 1);
      });
    },
    // 更改样品
    handleChangeSample(val) {
      console.log("更改样品", val);
      this.upload.data.registrationSlidesSampleId = val;
      console.log("this.importDataList", this.importDataList);
      if (this.importDataList.length != 0) {
        let arr = this.importDataList.map((item) => {
          return {
            registrationSlidesId: item.registrationSlidesId,
            slidesNumber: item.slidesNumber,
            registrationSlidesSampleName: item.registrationSlidesSampleName,
            detectionTime: item.detectionTime,
            holeOne: item.holeOne,
            holeTwo: item.holeTwo,
          };
        });
        let form = {
          registrationSlidesSampleId: val,
          registrationSlidesBos: arr,
        };
        this.loadingCalculate = true;
        changeSample(form)
          .then((response) => {
            this.importDataList = response.data;
            this.loadingCalculate = false;
          })
          .catch((response) => {
            this.loadingCalculate = false;
          });
      }
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 文件移除
    handleRemove(file, fileList) {
      console.log("handleRemove", fileList);
      this.fileList = fileList;
      this.importDataList = [];
    },
    // 点击文件预览
    handlePreview(file, fileList) {},
    // 文件移除前
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(() => {
        this.importDataList = [];
      });
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      if (response.code == 500) {
        this.$modal.msgError(response.msg);
        return;
      }
      if (response.data && response.data.length != 0) {
        this.importDataList.push(...response.data);
      }
      this.fileList = fileList;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 上传前格式校验
    beforeAvatarUpload(file) {
      const isTxt = file.type === "text/plain";
      if (!isTxt) {
        this.$message.warning("请上传txt格式的文件!");
        return false;
      }
      if (!this.form.registrationSlidesSampleId) {
        this.$message.error("请选择对照组!");
        return false;
      }
      return true;
    },
    // 超出数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    // 关闭
    closeExam() {
      if (this.status != "3") {
        this.$refs.upload.clearFiles();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.operation {
  margin-bottom: 15px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.myupload {
  margin-bottom: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
.el-table .warning-row {
  background: rgb(228, 13, 13);
}
.searchcontainer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -10px;
}
.viewform {
  justify-content: flex-end;
}
.viewbind .el-form {
  margin-left: -20px;
}
</style>
